package com.ewei.web.common.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.ewei.web.common.exception.ExceptionUtils;
import com.ewei.web.common.exception.MessageRuntimeException;

/**
 * Http协议工具类(还待完善)
 * @author David
 *
 */
public class HttpUtils {
	private static final Logger logger = LogManager.getLogger(HttpUtils.class);
	private HttpUtils(){
	}
	/**
	 * check the request is ajax
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request){
		return request.getHeader("X-Requested-With") != null 
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
	}
	/**
	 * change the value of 'If-Modifed-Since' to long type
	 * @param request
	 * @return
	 */
	public static long modifyDate(HttpServletRequest request){
		String dateStr = request.getHeader("If-Modified-Since");
		if(null!=dateStr){
			SimpleDateFormat format = new SimpleDateFormat("EEE,d MMM yyyy HH:mm:ss 'GMT'",Locale.US);
			try {
				return format.parse(dateStr).getTime();
			} catch (ParseException e) {
				logger.info(ExceptionUtils.traceMsg(e));
				throw new MessageRuntimeException(e);
			}
		}
		return -1;
	}
	/**
	 * get cookie from request
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request,String cookieName){
		Cookie[] cookies = request.getCookies();
		if(null != cookies){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals(cookieName)){
					return cookie;
				}
			}
		}
		return null;
	}
	/**
	 * add cookie to response with compressing
	 * @param response
	 * @param cookie
	 */
	public static void compressCookie(HttpServletResponse response,Cookie cookie){
		try {
			ByteArrayOutputStream byteout = new ByteArrayOutputStream();
			DeflaterOutputStream dfout = new DeflaterOutputStream(byteout);
			dfout.write(cookie.getValue().getBytes());
			dfout.close();
			//Base64 encode 
			String result = new BASE64Encoder().encode(byteout.toByteArray());
			cookie.setValue(result);
			response.addCookie(cookie);
		} catch (IOException e) {
			logger.info(ExceptionUtils.traceMsg(e));
			throw new MessageRuntimeException("compress failed!");
		}
	}
	/**
	 * get cookie from request with uncompressing
	 * @param cookie
	 * @return
	 */
	public static Cookie umpressCookie(HttpServletRequest request,String cookieName){	
		try{
			Cookie cookie = getCookie(request, cookieName);
			if(null != cookie){
				String compress = cookie.getValue();
				byte[] temp = new BASE64Decoder().decodeBuffer(compress);
				ByteArrayInputStream bytein = new ByteArrayInputStream(temp);
				ByteArrayOutputStream byteout = new ByteArrayOutputStream();
				InflaterInputStream ifin = new InflaterInputStream(bytein);
				int len = -1;
				byte[] b = new byte[1024];
				while((len = ifin.read(b))>0){
					byteout.write(b,0,len);
				}
				ifin.close();
				cookie.setValue(byteout.toString("IS0-8859"));
			}
			return cookie;
		}catch(IOException e){
			logger.info(ExceptionUtils.traceMsg(e));
			throw new MessageRuntimeException("uncompress failed!");
		}
	}
}
